﻿using HDM.NexusEngine.Core;
using HDM.NexusEngine.Input;
using Tao.OpenGl;

namespace HDM.NexusEngine.Shooter.GameStates
{
    public class InnerGameState : IGameObject
    {
        private readonly Renderer _renderer = new Renderer();
        private InputManager _input;
        private readonly StateSystem _system;
        private readonly PersistantGameData _gameData;
        private double _gameTime;
        private Level _level;
        private readonly TextureManager _textureManager;

        public InnerGameState(StateSystem system, InputManager input, TextureManager textureManager, PersistantGameData gameData)
        {
            _system = system;
            _input = input;
            _gameData = gameData;
            _textureManager = textureManager;
            OnGameStart();
        }

        public void OnGameStart()
        {
            _level = new Level(_input, _textureManager, _gameData);
            _gameTime = _gameData.CurrentLevel.Time;
        }

        public void Update(double elapsedTime)
        {
            _level.Update(elapsedTime, _gameTime);
            _gameTime -= elapsedTime;

            if (_gameTime <= 0)
            {
                OnGameStart();
                _gameData.JustWon = true;
                _system.ChangeState("game_over");
            }

            if (_level.Player.IsDead)
            {
                OnGameStart();
                _gameData.JustWon = false;
                _system.ChangeState("game_over");
            }
        }

        public void Render()
        {
            Gl.glClearColor(1, 0, 1, 0);
            Gl.glClear(Gl.GL_COLOR_BUFFER_BIT);
            _level.Render(_renderer);
            _renderer.Render();
        }
    }
}